import {
	createRouter,
	createWebHashHistory
} from "vue-router";
import _ from "lodash";
import store from "@/store";
import signIn from "@/views/signIn/signIn";

const basicLayout = () => import("@/views/layout/basicLayout.vue");

export const constantRouter = [{
	path: "/",
	name: "signIn",
	component: signIn,
	meta: {
		anonymous: true
	}
}];

export const asyncRouter = [{
		path: "/dashboard",
		component: basicLayout,
		children: [{
			path: "/dashboard",
			name: "dashboard",
			component: () => import("@/views/dashboard/dashboard.vue"),
			meta: {
				menuName: "概览"
			}
		}]
	},
	{
		path: "/system",
		component: basicLayout,
		children: [{
				path: "/system/profile",
				name: "profile",
				component: () => import("@/views/system/Profile.vue")
			}
		]
	}
];

const router = createRouter({
	history: createWebHashHistory(),
	routes: constantRouter
});


// 是否有权限访问某个路径
const hasPermission = toPath => {
	const links = _.map(store.state.menus, "link");
	return _.indexOf(links, toPath) > 0;
};

// 根据菜单生成路由的菜单元数据
const generateMenuName = route => {
	const menu = _.find(store.state.menus, {
		link: route.path
	});
	if (!menu) {
		return;
	}
	const menuName = menu.menuName;
	if (route.meta) {
		route.meta.menuName = menuName;
	} else {
		route.meta = {
			menuName
		};
	}
	_.forEach(route.children, child => {
		generateMenuName(child);
	});
};

// 动态生成路由表
const generateRoutes = () =>
	_.filter(asyncRouter, route => {
		const flag = hasPermission(route.path);
		if (flag) {
			generateMenuName(route);
		}
		return flag;
	});

// 导航之前拦截器
router.beforeEach(async (to, from, next) => {
	console.log('导航之前拦截器1');
	if (to.meta.anonymous) {
		next();
		return;
	}

	// 没有Token，尝试从本地存储中重新加载Token
	if (store.state.token == null) {
		const token = localStorage.getItem("token");
		if (token != null && token.toUpperCase() !== "NULL") {
			store.commit("setToken", token);
		}
	}

	// 有Token
	if (store.state.token != null) {
		console.log('导航之前拦截器2');
		// 没有菜单信息，重新从服务器加载菜单
		if (store.state.menus.length === 0) {
			await store
				.dispatch("reloadUserAuthority")
				.then(() => {
					const routes = generateRoutes();
					console.log('组装动态路由：', routes);
					// router.addRoutes(routes);//废弃
					routes.forEach(item => {
						router.addRoute(item);
					});
					next({
						...to,
						replace: true
					});
				})
				.catch(() => {
					next("/");
				});
		} else if (hasPermission(to.path)) {
			console.log('导航之前拦截器3');
			next();
		} else {
			console.log('导航之前拦截器4');
			// 无权限访问，返回到登陆页面
			next("/");
		}
	} else {
		console.log('导航之前拦截器5');
		// 本地没有Token，需要重新登陆
		next("/");
	}
});


export default router;
